package com.grow.greenhouse.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.grow.greenhouse.domain.Historyexception;
import com.grow.greenhouse.domain.Userthreshold;
import com.grow.greenhouse.once.UserContext;
import com.grow.greenhouse.service.HistoryexceptionService;
import com.grow.greenhouse.service.UserthreholdService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Component
@Slf4j
public class MQListener {


    @Resource
    private UserthreholdService userthreholdService;

    @Resource
    private HistoryexceptionService historyexceptionService;

    Gson gson = new Gson();


    @RabbitListener(queues = "Exception_Check")
    public void onMessage(Map<String,String> lastValueMap) {

        Map<String,String> translateMap = Stream.of(new String[][]{
                {"airMoisture","棚内湿度"},
                {"illumination","光照强度"},
                {"airTemp","棚内温度"},
                {"PHvalue","土壤PH值"},
                {"carbonDioxide","二氧化碳含量"},
                {"soilTemp","土壤温度"},
                {"soilMoisture","土壤湿度"}

        }).collect(Collectors.toMap(data -> data[0], data -> data[1]));
        QueryWrapper<Userthreshold> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",UserContext.getUserId());
        String shedName = UserContext.getShedName();
        queryWrapper.eq("shedName",shedName);
        Userthreshold userthreshold = userthreholdService.getOne(queryWrapper);
         log.info(lastValueMap.toString());
         // map中的内容如下：
         // soilMositure -> 50,75,100
        //  soilTemp -> 12,20.5,30
         Map<String,List<String>> thresholdMap = new HashMap<>();
        lastValueMap.forEach((key,value)->{
            String userthreholdByString = userthreshold.getUserthreholdByIndicator(key);
            thresholdMap.put(key,gson.fromJson(userthreholdByString, new TypeToken<List<String>>() {
            }.getType()));
        });

        log.info(thresholdMap.toString());
        lastValueMap.forEach((key,value)->{
            Historyexception historyexception = new Historyexception();
            List<String> threshold = thresholdMap.get(key);
            BigDecimal minValue = BigDecimal.valueOf(Double.parseDouble(threshold.get(0)));
            BigDecimal maxValue = BigDecimal.valueOf(Double.parseDouble(threshold.get(2)));
            BigDecimal nowValue = BigDecimal.valueOf(Double.parseDouble(value));
            if(nowValue.doubleValue() > maxValue.doubleValue()){
                BigDecimal overNum = nowValue.subtract(maxValue);
                if(overNum.doubleValue()<3){
                    historyexception.setExceptionStatus(0);
                }
                else{
                    historyexception.setExceptionStatus(1);
                }
                historyexception.setIndicatorStatus(translateMap.getOrDefault(key,key)+"过高");
                historyexception.setPromptContent("超过预警"+overNum);
            }
            else if(nowValue.doubleValue() < minValue.doubleValue()){
                BigDecimal lowerNum =minValue.subtract(nowValue);
                if(lowerNum.doubleValue()<3){
                    historyexception.setExceptionStatus(0);
                }
                else{
                    historyexception.setExceptionStatus(1);
                }
                historyexception.setIndicatorStatus(translateMap.getOrDefault(key,key)+"过低");
                historyexception.setPromptContent("低于预警"+lowerNum);
            }
            if(historyexception.getExceptionStatus() != null){
                historyexception.setUserId(UserContext.getUserId());
                historyexception.setBelongShedName(UserContext.getShedName());
                historyexceptionService.save(historyexception);
            }
        });

    }

}
